import { In } from 'typeorm';
import { ListParams } from '../interface';
import { createOrder, createSearch } from '../utils/ormHelper';

/*
 * @Author: 颜礼田 2564217790@qq.com
 * @Date: 2024-09-07 10:40:05
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-24 16:32:34
 * @FilePath: /webServer/src/service/impl.ts
 * @Description: 这是所有服务的抽象类
 */
export abstract class ServicesImpl {
  /**
   * 当前服务
   */
  abstract services: any;

  /**
   * 关联集
   */
  abstract relations: Array<string>;

  /**
   * 保存数据
   * @param params
   * @returns
   */
  async save(params: any) {
    return await this.services.save(params);
  }

  /**
   * 软删除
   * @param id
   * @returns
   */
  async remove(id: string) {
    return await this.services.softRemove({ id });
  }

  /**
   * 真删除
   * @param id
   * @returns
   */
  async realRemove(id: string) {
    const entity = await this.services.findOne({
      where: { id },
    });
    return await this.services.remove(entity);
  }

  /**
   * 获取单条数据
   * @param id
   * @returns
   */
  async info(id: string) {
    return await this.services.findOne({
      where: { id },
      relations: this.relations,
    });
  }

  /**
   * 通过字段查找一条数据
   * @param whereSchema
   * @returns
   */
  async findByFields(whereSchema: { [key: string]: any }) {
    return await this.services.findOne({ where: whereSchema });
  }

  /**
   * 通过字段查找数据列表
   * @param whereSchema
   * @returns
   */
  async findMoreByFields(whereSchema: { [key: string]: any }) {
    return await this.services.find({
      where: whereSchema,
      relations: this.relations,
    });
  }

  /**
   * 通过id集合查找数据
   * @param ids
   * @param useRelations
   * @returns
   */
  async findByIds(ids: Array<string>, useRelations = false) {
    return await this.services.find({
      where: {
        id: In(ids),
      },
      relations: useRelations ? this.relations : [],
    });
  }

  /**
   * 获取分页数据
   * @param params
   * @returns
   */
  async list(params: ListParams<any>): Promise<any> {
    const [list, total] = await this.services.findAndCount({
      where: createSearch(params.search),
      skip: (params.pageNum - 1) * params.pageSize,
      take: params.pageSize,
      order: createOrder(params?.sortField, params?.sortMethod),
      relations: this.relations,
    });

    return { list, total };
  }

  /**
   * 获取最新添加的数据，默认为5条
   * @param count
   * @param whereSchema
   * @returns
   */
  async lastedList(count = 5, whereSchema?: { [key: string]: any }) {
    return this.services.find({
      where: whereSchema,
      order: { createAt: 'DESC' },
      take: count,
    });
  }
}
